﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace PaymentHelper.Core.MultiLanguage
{
    public static class LanguageManager
    {
        public static string DefaultLanguageCode { get; set; }
        private static IList<string> _supportedLanguage;

        /// <summary>
        /// Init default code language and list of supported languages
        /// </summary>
        /// <param name="listLanguages">Info for initialization</param>
        public static void InitMultiLanguage(Dictionary<string,bool> listLanguages)
        {
            _supportedLanguage = listLanguages.Keys.ToList();
            var defaultLanguage = listLanguages.FirstOrDefault(l => l.Value == true);

            DefaultLanguageCode = defaultLanguage.Key;
        }

        /// <summary>
        /// Get language container of method 
        /// </summary>
        /// <param name="eXLanguage"> XML element which contains language info  </param>
        /// <returns></returns>
        public static LanguageContainer GetLanguageContainer(XElement eXLanguage)
        {
            if (eXLanguage == null)
                throw new Exception("Not exist language configuration for specified method !");

            LanguageContainer languageContainer = new LanguageContainer();

            var languages = eXLanguage.Descendants("Language");
            foreach (var language in languages)
            {
                string code = language.Attribute("Code").Value;
                LanguagePackage package = new LanguagePackage()
                {
                    Code = code,
                    IsDefault = code.Equals(LanguageManager.DefaultLanguageCode,StringComparison.InvariantCultureIgnoreCase),
                    LanguageResources = ParseLanguagePackage(language)
                };
                languageContainer[code] = package;
            }

            return languageContainer;
        }

        /// <summary>
        /// Get list of resources of language specified
        /// </summary>
        /// <param name="element"> XML element which contains info of resources </param>
        /// <returns></returns>
        private static Dictionary<string,string> ParseLanguagePackage(XElement element)
        {
            Dictionary<string, string> listResource = new Dictionary<string, string>();
            
            var resources = element.Descendants("Resource");
            foreach(var resource in resources)
            {
                string id = resource.Attribute("Id").Value.ToLower();
                string value = resource.Value.Trim();
                
                listResource.Add(id, value);
            }

            return listResource;
        }
    }
}
